package Config;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.json.JSONObject;

/**
 *
 * @author Administrador
 */
public class ConfigReader {

	private static String CONFIG_FILE = "res/config.txt";
	
		
   public static String getString(String token) throws Exception{       
       JSONObject obj = getJSONObject();
       String value=null;
       if(obj.has(token)) value = obj.getString(token);
       return value;
   }

   public static int getInt(String token) throws Exception{       
	   JSONObject obj = getJSONObject();
       int value=-1;
       if(obj.has(token)) value = obj.getInt(token);
       return value;
   }

   
   public static boolean getBool(String token) throws Exception{       
	   JSONObject obj = getJSONObject();
       return obj.getBoolean(token);

   }
   
  
   public static boolean has(String token) throws Exception{
	   JSONObject obj = getJSONObject();
	   return (obj.has(token));
   }
   
    static private String getContents(File aFile) {        
        StringBuilder contents = new StringBuilder();
        try {
          BufferedReader input =  new BufferedReader(new FileReader(aFile));
          try {
            String line = null;        
            while (( line = input.readLine()) != null){
              contents.append(line);
        //          contents.append(System.getProperty("line.separator"));
            }
          }
          finally {
            input.close();
          }
        }
        catch (IOException ex){
          ex.printStackTrace();
        }

        return contents.toString();
    }
    
    
    private static JSONObject getJSONObject() throws Exception
    {
    	String CONFIG_KEY = "config_file_path";
        File file = new File(CONFIG_FILE);
        String strFile = getContents(file);
        JSONObject obj = new JSONObject(strFile);
        
        if (obj.has(CONFIG_KEY))
        {
        	file = new File(obj.getString(CONFIG_KEY));
           // System.out.println(file.getAbsolutePath());
            strFile = getContents(file);
            obj = new JSONObject(strFile);

        }

        return obj;
    }    
}
